var index={
    regex:[
        {"s_desc":"集团工号","s_regex":"/^[0-9A-Za-z\\u4e00-\\u9fa5]{4,20}$/"},
        {"s_desc":"集团邮箱","s_regex":"/^([a-zA-Z]|[0-9])(\\w|\\-)+@(mail.foxconn.com)|(foxconn.com)$/"},
        {"s_desc":"身份证号","s_regex":"/(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)/"},
        {"s_desc":"邮箱","s_regex":"/^([a-zA-Z0-9]+[_|_|\\-|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+\\.[a-zA-Z]{2,6}$/"},
        {"s_desc":"日期","s_regex":"/^\\d{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[1-2][0-9]|3[0-1])$/"},
        {"s_desc":"手机号","s_regex":"/(^、\d{11}$)|(^([6|9])\\d{7}$)|(^[6]([8|6])\\d{5})/"},
        {"s_desc":"整数","s_regex":"/^\\d{1,16}$/"}
    ],
    config:{datatype:[]},
    Show:function(){
        m.request({
            method:"GET",
            url:"config.json",
        }).then(function(res){
            index.config=res;
            document.querySelector("title").innerText=index.config.title;
            m.render(document.body,m(index))
        })
    },
    view:function(){
        return [
            m("div.top",index.config.title),
            m("div.map",[
                m("button.map_bt_active",{onclick:index.Change},"数据字典"),
                m("button.map_bt",{onclick:index.Change},"表结构"),
                m("button.map_bt",{onclick:index.Change},"接口定义")
            ]),
            m("div.page"),
            m(page2),
            m("datalist#datatype",index.config.datatype.map(function(val){
                return m("option",{value:val})
            })),
            m("button.run",{onclick:page2.Show},"生成"),
            m("div.regex_div",[
                m("button.regex",{onclick:index.RegexShow},"常用正则表达式"),
                index.regex.map(_r=>{
                    return m("div.regex_line",[
                        m("div.regex_tag",_r.s_desc),
                        m("div.regex_desc",{onclick:index.Copy},_r.s_regex)
                    ])
                })
            ])
            
        ]
    },
    oncreate:function(){
        document.querySelector(".map_bt_active").click();
    },
    Change:function(){
        document.querySelectorAll(".map_bt,.map_bt_active").forEach((bt)=>{
            // console.log(bt.getAttribute("class"));
            bt.setAttribute("class","map_bt");
        });
        this.setAttribute("class","map_bt_active");
        if(this.innerText=="数据字典"){
            dictionary.Show();
            return;
        }
        if(this.innerText=="表结构"){
            database.Show();
            return;
        }
        if(this.innerText=="接口定义"){
            interface.Show();
            return;
        }
    },
    RegexShow:function(){
        if(this.parentNode.getAttribute("class")=="regex_div"){
            this.parentNode.setAttribute("class","regex_div2");
        }else{
            this.parentNode.setAttribute("class","regex_div");
        }
    },
    Copy:function(){
        navigator.clipboard.writeText(this.innerText);
        this.style.content="已复制";
    }
}


//数据指定处理
var dictionary={
    list:[],
    Show:function(){
        m.request({
            method:"GET",
            url:"query.php?dictionary=1"
        }).then(function(res){
            dictionary.list=[];
            if(res!={}){
                count=1;
                for(var key in res){
                    dictionary.list.push({
                        count:count,
                        desc:res[key].desc,
                        key:key,
                        content:res[key].content,
                        type:res[key].type,
                        min:res[key].min,
                        max:res[key].max,
                        regex:res[key].regex
                    });
                    count++;
                }
                console.log(dictionary.list);
            }
            m.render(document.querySelector(".page"),m(dictionary));
        })
    },
    view:function(){
        return [
            m("table.tbl",[
                m("tr",[
                    m("th","编号"),
                    m("th","中文名称"),
                    m("th","英文名称"),
                    m("th","规则简述"),
                    m("th","类别"),
                    m("th","最小字符"),
                    m("th","最大字符"),
                    m("th","正则表达式")
                ]),
                dictionary.list.map(function(tr){
                    return m("tr",{onclick:dictionary.InputTr},[
                        m("td",tr.count),
                        m("td",tr.desc),
                        m("td",tr.key),
                        m("td",tr.content),
                        m("td",tr.type),
                        m("td",tr.min),
                        m("td",tr.max),
                        m("td",tr.regex)
                    ])
                })
            ]),
            m("div.bts",[
                m("button",{onclick:dictionary.AddTr},"新增一行")
            ])
        ]
    },
    AddTr:function(){
        var tbl=document.querySelector(".tbl");
        var tr=tbl.insertRow(tbl.rows.length);
        tr.addEventListener("click",dictionary.InputTr);
        tbl.rows[0].querySelectorAll("th").forEach((th)=>{
            var elem=document.createElement("input");
            elem.type="text";
            if(th.innerText=="编号" || th.innerText=="最小字符"|| th.innerText=="最大字符"){
                elem.type="number";
                elem.value=th.innerText=="编号"?tbl.rows.length-1:0;
            }
            if(th.innerText=="类别"){
                elem.setAttribute("list","datatype");
            }
            elem.addEventListener("blur",dictionary.TextTr);
            var td=tr.insertCell();
            td.appendChild(elem);
            if(th.innerText=="英文名称"){
                td.querySelector("input").select();
            }
        });
    },
    InputTr:function(){
        if(this.querySelector("input")){
            return;
        }
        var tbl=this.parentNode;
        this.querySelectorAll("td").forEach((td,index)=>{
            var input=document.createElement("input");
            input.type="text";
            input.value=td.innerText;
            if(tbl.rows[0].cells[index].innerText=="类别"){
                input.setAttribute("list","datatype");
            }
            input.addEventListener("blur",dictionary.TextTr);
            td.innerHTML="";
            td.appendChild(input);
        });
        event.target.querySelector("input").select();
        event.target.querySelector("input").addEventListener("blur",dictionary.TextTr);
    },
    TextTr:function(){
        var tbl=document.querySelector(".tbl");
        tbl.querySelectorAll("input").forEach((input)=>{
            // console.log(input);
            input.parentNode.innerText=input.value;
        });
        
        var dictionary_json={};
        for(var i=1;i<tbl.rows.length;i++){
            if(tbl.rows[i].cells[2].innerText==""){
                tbl.deleteRow(i);
                break;
            }
            dictionary_json[tbl.rows[i].cells[2].innerText]={
                "desc":tbl.rows[i].cells[1].innerText,
                "content":tbl.rows[i].cells[3].innerText,
                "type":tbl.rows[i].cells[4].innerText,
                "min":tbl.rows[i].cells[5].innerText,
                "max":tbl.rows[i].cells[6].innerText,
                "regex":tbl.rows[i].cells[7].innerText
            };
        }
        var postData=new FormData();
        postData.append("dictionary",JSON.stringify(dictionary_json));
        m.request({
            method:"POST",
            url:"save.php",
            body:postData
        }).then(function(res){
            console.log(res);
        })
    }
}

//数据库处理
var database={
    list:[],
    view:function(){
        return [
            m("div.boxes",database.ShowTable()),
            m("datalist#dict",dictionary.list.map((item)=>{
                return m("option",{value:item.key},item.desc);
            })),
            m("div.bts",[
                m("button",{onclick:database.AddTable},"新增表")
            ])
        ]
    },
    ShowTable:function(){
        return database.list.map(function(box){
            var jsonToArray=[];
            for(var key in box.column){
                jsonToArray.push({
                    key:key,
                    desc:box.column[key].desc,
                    type:box.column[key].type,
                    isNull:box.column[key].isNull,
                    index:box.column[key].index,
                });
            }
            return m("div.box",[
                m("div.tbl_name",[
                    m("input[type=text]",{placeholder:"表名称",value:box.table}),
                    m("button",{onclick:database.AddTr},"新增栏位")
                ]),
                m("table.tbl",[
                    m("tr",[
                        m("th","栏位"),
                        m("th","栏位名称"),
                        m("th","类型"),
                        m("th","是否可空"),
                        m("th","索引")
                    ]),
                    jsonToArray.map(function(item){
                        return m("tr",{onclick:database.InputTr},[
                            m("td",item.key),
                            m("td",item.desc),
                            m("td",item.type),
                            m("td",item.isNull),
                            m("td",item.index)
                        ])
                    })
                ])
            ])
        })
    },
    AddTable:function(){
        database.list.push({
            "key":"",
            "desc":"",
            "type":"",
            "isNull":"",
            "index":"",
        });
        m.render(document.querySelector(".boxes"),database.ShowTable());
    },
    Show:function(){
        // m.render(document.querySelector(".page"),m(database));
        database.list=[];
        m.request({
            method:"GET",
            url:"query.php?database=1"
        }).then(function(res){
            console.log(res);
            database.list=res;
            m.render(document.querySelector(".page"),m(database));
        })
    },
    AddTr:function(){
        if(this.parentNode.parentNode.querySelector(".tbl_name").querySelector("input").value==""){
            alert("先填写表名称");
            return;
        }
        var tbl=this.parentNode.parentNode.querySelector("table");
        var count=tbl.rows.length-1;
        var tr=tbl.insertRow(count+1);
        tr.addEventListener("click",database.InputTr);
        tbl.rows[0].querySelectorAll("th").forEach((elem) => {
            var input=document.createElement("input");
            input.type="text";
            if(elem.innerText=="栏位"){
                input.setAttribute("list","dict");
            }
            input.addEventListener("input",database.QueryDict);
            input.addEventListener("blur",database.TextTr);
            var td=tr.insertCell();
            td.appendChild(input);
            if(elem.innerText=="栏位"){
                input.select();
            }
        });
    },
    QueryDict:function(){
        var tr=this.parentNode.parentNode;
        for(var i=0;i<dictionary.list.length;i++){
            if(this.value==dictionary.list[i].key){
                tr.querySelectorAll("input")[1].value=dictionary.list[i].desc;
                tr.querySelectorAll("input")[2].value=dictionary.list[i].type;
                if(dictionary.list[i].type=="string"){
                    tr.querySelectorAll("input")[2].value="varchar("+dictionary.list[i].max+")";
                }
                tr.querySelectorAll("input")[3].value=dictionary.list[i].min==0?"是":"否";
            }
        }
    },
    TextTr:function(){
        var tbl=this.parentNode.parentNode.parentNode;
        tbl.querySelectorAll("input").forEach(elem => {
            elem.parentNode.innerText=elem.value;
        });
        var database_array=[];
        for (let i = 0; i < tbl.rows.length; i++) {
            const element = tbl.rows[i];
            if(element.cells[0].innerText==""){
                tbl.deleteRow(i);
                break;
            }
        }
        for (let i = 0; i < document.querySelectorAll(".box").length; i++) {
            var table_name=document.querySelectorAll(".box")[i].querySelector(".tbl_name").querySelector("input").value;
            if(table_name==""){
                break;
            }
            var table_data=document.querySelectorAll(".box")[i].querySelector(".tbl");
            var database_json={};
            database_json["table"]=table_name;
            database_json["column"]={};
            for(var iRow=1;iRow<table_data.rows.length;iRow++){
                database_json["column"][table_data.rows[iRow].cells[0].innerText]={
                    "desc":table_data.rows[iRow].cells[1].innerText,
                    "type":table_data.rows[iRow].cells[2].innerText,
                    "isNull":table_data.rows[iRow].cells[3].innerText,
                    "index":table_data.rows[iRow].cells[4].innerText
                };
            }
            database_array.push(database_json);
        }
        console.log(database_array);
        var postData=new FormData();
        postData.append("database",JSON.stringify(database_array));
        m.request({
            method:"POST",
            url:"save.php",
            body:postData
        }).then(function(res){
            console.log(res);
        })
    },
    InputTr:function(){
        if(this.querySelector("input")){
            return;
        }
        var tbl=this.parentNode;
        this.querySelectorAll("td").forEach((td,index)=>{
            var input=document.createElement("input");
            input.type="text";
            input.value=td.innerText;
            if(tbl.rows[0].cells[index].innerText=="栏位"){
                input.setAttribute("list","dict");
            }
            input.addEventListener("blur",database.TextTr);
            td.innerHTML="";
            td.appendChild(input);
        });
        event.target.querySelector("input").select();
    },
}

//接口结构
var interface={
    list:[],
    view:function(){
        return [
            m("div.urls",[
                interface.ShowURL()
            ]),
            m("datalist#dict",dictionary.list.map((item)=>{
                return m("option",{value:item.key},item.desc);
            })),
            m("datalist#yesno",[
                m("option",{value:"是"}),
                m("option",{value:"否"})
            ]),
            m("div.bts",[
                m("button",{onclick:interface.AddURL},"新增接口")
            ])
        ]
    },
    Show:function(){
        interface.list=[];
        m.request({
            method:"GET",
            url:"query.php?interface=1"
        }).then(function(res){
            interface.list=res;
            m.render(document.querySelector(".page"),m(interface));
        })
    },
    ChangeBox:function(){
        this.parentNode.parentNode.querySelectorAll(".box_content").forEach((elem)=>{
            elem.style.height=this.innerText=="收起"?"0px":"auto";
            elem.style.transition="all 0.3s";
        });
        
        this.innerText=this.innerText=="收起"?"展开":"收起";
    },
    ShowURL:function(){
        return interface.list.map(function(item){
            var request=[];
            var response=[];
            for(var key in item.request){
                request.push({key:key,desc:item.request[key].desc,type:item.request[key].type,usecase:item.request[key].usecase,regex:item.request[key].regex,isMust:item.request[key].isMust});
            }
            for(var key in item.response){
                response.push({key:key,desc:item.response[key].desc,type:item.response[key].type,usecase:item.response[key].usecase,regex:item.response[key].regex,isMust:item.response[key].isMust});
            }
            console.log(request);
            return m("div.url",[
                m("div.box_title",[
                    m("input[type=text].box_name",{placeholder:"接口名称",onblur:interface.Save,value:item.desc}),
                    m("select.box_method",[
                        m("option",{value:"GET",selected:item.method=="GET"?true:false},"GET index.php?p="),
                        m("option",{value:"POST",selected:item.method=="POST"?true:false},"POST index.php?p=")
                    ]),
                    m("input[type=text].box_input",{onblur:interface.Save,value:item.url}),
                    m("button",{onclick:interface.ChangeBox},"展开")
                ]),
                m("div.box_content",{style:"height:0px;"},[
                    m("div.box_tag","Request"),
                    m("div.box_line",[
                        m("div.box_sub","Body"),
                        m("button",{onclick:interface.AddTr},"新增一行")
                    ]),
                    m("table.tbl2",[
                        m("tr",[
                            m("th","参数"),
                            m("th","说明"),
                            m("th","类型"),
                            m("th","举例"),
                            m("th","约束"),
                            m("th","是否必须")
                        ]),
                        request.map(function(_r){
                            return m("tr",{onclick:interface.InputTr},[
                                m("td",_r.key),
                                m("td",_r.desc),
                                m("td",_r.type),
                                m("td",_r.usecase),
                                m("td",_r.regex),
                                m("td",_r.isMust)
                            ])
                        })
                    ]),
                ]),
                m("div.box_content",{style:"height:0px;"},[
                    m("div.box_tag","Response"),
                    m("div.box_line",[
                        m("div.box_sub","JSON"),
                        m("button",{onclick:interface.AddTr},"新增一行")
                    ]),
                    m("table.tbl2",[
                        m("tr",[
                            m("th","参数"),
                            m("th","说明"),
                            m("th","类型"),
                            m("th","举例"),
                            m("th","约束"),
                            m("th","是否必须")
                        ]),
                        response.map(function(_r){
                            return m("tr",{onclick:interface.InputTr},[
                                m("td",_r.key),
                                m("td",_r.desc),
                                m("td",_r.type),
                                m("td",_r.usecase),
                                m("td",_r.regex),
                                m("td",_r.isMust)
                            ])
                        })
                    ])
                ]),
                m("button.url_button",{onclick:function(){
                    interface.list.push({
                        desc:"",url:"",method:"GET",
                        request:item.request,
                        response:item.response
                    });
                    m.render(document.querySelector(".urls"),interface.ShowURL());
                }},"复制新增")
            ])
        })
    },
    AddURL:function(){
        interface.list.push({
            "url":"",
            "desc":"",
            "method":"",
            "request":{},
            "response":{}
        });
        m.render(document.querySelector(".urls"),interface.ShowURL());
    },
    AddTr:function(){
        var _parent=this.parentNode.parentNode;
        var tbl=_parent.querySelector(".tbl2");
        var tr=tbl.insertRow();
        tr.addEventListener("click",interface.InputTr);
        tbl.rows[0].querySelectorAll("th").forEach(th=>{
            var td=tr.insertCell();

            var input=document.createElement("input");
            input.type="text";
            if(th.innerText=="参数"){
                input.setAttribute("list","dict");
                input.addEventListener("input",interface.QueryDict);
            }
            if(th.innerText=="类型"){
                input.setAttribute("list","datatype");
            }
            if(th.innerText=="是否必须"){
                input.setAttribute("list","yesno");
                input.value="是";
            }
            input.addEventListener("blur",interface.TextTr);

            td.appendChild(input);
        });
    },
    QueryDict:function(){
        for(var i=0;i<dictionary.list.length;i++){
            if(this.value==dictionary.list[i].key){
                this.parentNode.parentNode.querySelectorAll("input")[2].value=dictionary.list[i].type;
                this.parentNode.parentNode.querySelectorAll("input")[1].value=dictionary.list[i].desc;
                if(dictionary.list[i].regex==""){
                    this.parentNode.parentNode.querySelectorAll("input")[4].value="len:"+dictionary.list[i].min+":"+dictionary.list[i].max;
                }else{
                    this.parentNode.parentNode.querySelectorAll("input")[4].value=dictionary.list[i].regex;
                }
            }
        }
    },
    TextTr:function(){
        var tbl=this.parentNode.parentNode.parentNode;
        
        tbl.querySelectorAll("input").forEach((elem)=>{
            elem.parentNode.innerHTML=elem.value;
        });

        interface.Save();
    },
    InputTr:function(){
        if(this.querySelector("input")){
            return;
        }
        var tbl=this.parentNode;
        this.querySelectorAll("td").forEach((td,index)=>{
            var input=document.createElement("input");
            input.type="text";
            if(tbl.rows[0].cells[index].innerText=="参数"){
                input.setAttribute("list","dict");
                input.addEventListener("input",interface.QueryDict);
            }
            if(tbl.rows[0].cells[index].innerText=="类型"){
                input.setAttribute("list","datatype");
            }
            if(tbl.rows[0].cells[index].innerText=="是否必须"){
                input.setAttribute("list","yesno");
                input.value="是";
            }
            input.addEventListener("blur",interface.TextTr);
            input.value=td.innerText;
            td.innerHTML="";
            td.appendChild(input);
        });
        event.target.querySelector("input").select();
    },
    Save:function(){
        var interface_arr=[];
        document.querySelectorAll(".url").forEach((url)=>{
            var interface_json={};
            interface_json["url"]=url.querySelector(".box_input").value;
            interface_json["desc"]=url.querySelector(".box_name").value;
            interface_json["method"]=url.querySelector(".box_method").value;
            if(interface_json["url"]!="" && interface_json["desc"]!=""){
                interface_arr.push(interface_json);
            }
            interface_json["request"]={};
            var request_tbl=url.querySelector(".tbl2");
            request_tbl.querySelectorAll("tr").forEach((tr,index)=>{
                if(index==0){
                    return;
                }
                if(tr.cells[0].innerText==""){
                    request_tbl.deleteRow(index);
                    return;
                }
                interface_json["request"][tr.cells[0].innerText]={
                    desc:tr.cells[1].innerText,
                    type:tr.cells[2].innerText,
                    usecase:tr.cells[3].innerText,
                    regex:tr.cells[4].innerText,
                    isMust:tr.cells[5].innerText
                };
            });
            interface_json["response"]={};
            var response_tbl=url.querySelectorAll(".tbl2")[1];
            response_tbl.querySelectorAll("tr").forEach((tr,index)=>{
                if(index==0){
                    return;
                }
                if(tr.cells[0].innerText==""){
                    response_tbl.deleteRow(index);
                    return;
                }
                interface_json["response"][tr.cells[0].innerText]={
                    desc:tr.cells[1].innerText,
                    type:tr.cells[2].innerText,
                    usecase:tr.cells[3].innerText,
                    regex:tr.cells[4].innerText,
                    isMust:tr.cells[5].innerText
                };
            });
        });
        if(interface_arr.length>0){
            var postData=new FormData();
            postData.append("interface",JSON.stringify(interface_arr));
            m.request({
                method:"POST",
                url:"save.php",
                body:postData
            }).then(function(res){
                console.log(res);
            })
        }
    }
}

//page2页面
var page2={
    view:function(){
        return m("div.page2",[
            m("div.page2_box",[
                m("div.page2_title","更新开发文件"),
                m("div.page2_line",[
                    m("div.page2_tag","选择功能"),
                    m("div.page2_input",[
                        m("input[type=checkbox].config",{value:"database",id:"id1",onclick:page2.AlertSelect}),
                        m("label",{for:"id1"},"database"),
                        m("input[type=checkbox].config",{value:"databaseadd",id:"id6"}),
                        m("label",{for:"id6"},"databaseinit"),
                        m("input[type=checkbox].config",{value:"document",id:"id2"}),
                        m("label",{for:"id2"},"document"),
                        m("input[type=checkbox].config",{value:"control",id:"id3"}),
                        m("label",{for:"id3"},"control"),
                        m("input[type=checkbox].config",{value:"controlinit",id:"id4",onclick:page2.AlertSelect}),
                        m("label",{for:"id4"},"controlinit"),
                        m("input[type=checkbox].config",{value:"model",id:"id5"}),
                        m("label",{for:"id5"},"model"),
                    ]),
                    m("button",{onclick:page2.Submit},"更新")
                ]),
                m("div.page2_line",[
                    m("iframe.page2_terminal")
                ]),
                m("button.page2_back",{onclick:page2.Hide},"关闭")
            ])
        ])
    },
    AlertSelect:function(){
        var _this=this;
        if(_this.checked){
            if(!confirm("选择该操作，会清空业务代码(包括DB)，是否确定？")){
                _this.checked=false;
            }
        }
    },
    Hide:function(){
        document.querySelector(".page2").style.display="none";
        document.querySelector(".page2_terminal").src="";
    },
    Show:function(){
        document.querySelector(".page2").style.display="block";
    },
    Submit:function(){
        var config='';
        document.querySelectorAll(".config").forEach(input=>{
            if(input.checked){
                config+=input.value+",";
            }
        });
        console.log(config);
        document.querySelector(".page2_terminal").src="../config-dev.php?config="+config;
    }
}


//入口函数
index.Show();